package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"log"

	"gorm.io/gorm"
)

// EmojiService 表情服务接口
type EmojiService interface {
	// 表情分类管理
	CreateEmojiCategory(req *model.CreateEmojiCategoryReq) (*model.EmojiCategory, error)
	GetEmojiCategory(id uint) (*model.EmojiCategory, error)
	GetEmojiCategoryList(req *model.EmojiCategoryListReq) (*model.EmojiCategoryListResp, error)
	UpdateEmojiCategory(id uint, req *model.UpdateEmojiCategoryReq) error
	DeleteEmojiCategory(id uint) error

	// 表情管理
	CreateEmoji(createdBy uint, req *model.CreateEmojiReq) (*model.Emoji, error)
	GetEmoji(id uint) (*model.Emoji, error)
	GetEmojiList(req *model.EmojiListReq) (*model.EmojiListResp, error)
	UpdateEmoji(id uint, req *model.UpdateEmojiReq) error
	DeleteEmoji(id uint) error

	// 前端获取表情包
	GetEmojis() (*model.GetEmojisResp, error)
	GetHotEmojis(limit int) ([]model.Emoji, error)
	RecordEmojiUsage(emojiID uint) error
}

// emojiService 表情服务实现
type emojiService struct {
	repo *repository.EmojiRepository
}

// NewEmojiService 创建表情服务
func NewEmojiService(repo *repository.EmojiRepository) EmojiService {
	return &emojiService{
		repo: repo,
	}
}

// ==================== 表情分类管理 ====================

// CreateEmojiCategory 创建表情分类
func (s *emojiService) CreateEmojiCategory(req *model.CreateEmojiCategoryReq) (*model.EmojiCategory, error) {
	category := &model.EmojiCategory{
		Name:        req.Name,
		Icon:        req.Icon,
		SortOrder:   req.SortOrder,
		Description: req.Description,
		IsEnabled:   true,
		IsSystem:    false,
	}

	if err := s.repo.CreateCategory(category); err != nil {
		return nil, err
	}

	log.Printf("[表情分类] 创建分类: %s", category.Name)
	return category, nil
}

// GetEmojiCategory 获取表情分类详情
func (s *emojiService) GetEmojiCategory(id uint) (*model.EmojiCategory, error) {
	category, err := s.repo.GetCategoryByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("表情分类不存在")
		}
		return nil, err
	}
	return category, nil
}

// GetEmojiCategoryList 获取表情分类列表
func (s *emojiService) GetEmojiCategoryList(req *model.EmojiCategoryListReq) (*model.EmojiCategoryListResp, error) {
	// 参数验证
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 20
	}

	categories, total, err := s.repo.GetCategoryList(req)
	if err != nil {
		return nil, err
	}

	return &model.EmojiCategoryListResp{
		List:     categories,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// UpdateEmojiCategory 更新表情分类
func (s *emojiService) UpdateEmojiCategory(id uint, req *model.UpdateEmojiCategoryReq) error {
	// 检查分类是否存在
	category, err := s.repo.GetCategoryByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("表情分类不存在")
		}
		return err
	}

	// 系统分类不允许某些操作
	if category.IsSystem && req.IsEnabled != nil && !*req.IsEnabled {
		return errors.New("系统内置分类不能禁用")
	}

	// 构建更新字段
	updates := make(map[string]interface{})
	if req.Name != "" {
		updates["name"] = req.Name
	}
	if req.Icon != "" {
		updates["icon"] = req.Icon
	}
	if req.SortOrder != nil {
		updates["sort_order"] = *req.SortOrder
	}
	if req.IsEnabled != nil {
		updates["is_enabled"] = *req.IsEnabled
	}
	if req.Description != "" {
		updates["description"] = req.Description
	}

	if len(updates) == 0 {
		return errors.New("没有需要更新的字段")
	}

	if err := s.repo.UpdateCategory(id, updates); err != nil {
		return err
	}

	log.Printf("[表情分类] 更新分类 ID: %d", id)
	return nil
}

// DeleteEmojiCategory 删除表情分类
func (s *emojiService) DeleteEmojiCategory(id uint) error {
	// 检查分类是否存在
	category, err := s.repo.GetCategoryByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("表情分类不存在")
		}
		return err
	}

	// 系统分类不允许删除
	if category.IsSystem {
		return errors.New("系统内置分类不能删除")
	}

	// 检查是否有表情使用此分类
	count, err := s.repo.CountEmojisByCategory(id)
	if err != nil {
		return err
	}
	if count > 0 {
		return errors.New("该分类下还有表情，无法删除")
	}

	if err := s.repo.DeleteCategory(id); err != nil {
		return err
	}

	log.Printf("[表情分类] 删除分类 ID: %d", id)
	return nil
}

// ==================== 表情管理 ====================

// CreateEmoji 创建表情
func (s *emojiService) CreateEmoji(createdBy uint, req *model.CreateEmojiReq) (*model.Emoji, error) {
	// 检查分类是否存在
	_, err := s.repo.GetCategoryByID(req.CategoryID)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("表情分类不存在")
		}
		return nil, err
	}

	// 检查表情代码是否重复
	exists, err := s.repo.CheckCodeExists(req.Code)
	if err != nil {
		return nil, err
	}
	if exists {
		return nil, errors.New("表情代码已存在")
	}

	// 验证表情类型
	if req.Type == model.EmojiTypeUnicode && req.Emoji == "" {
		return nil, errors.New("Unicode 表情必须提供 emoji 字段")
	}
	if req.Type == model.EmojiTypeCustom && req.ImageURL == "" {
		return nil, errors.New("自定义表情必须提供 imageUrl 字段")
	}

	emoji := &model.Emoji{
		CategoryID: req.CategoryID,
		Name:       req.Name,
		Code:       req.Code,
		ImageURL:   req.ImageURL,
		Emoji:      req.Emoji,
		Type:       req.Type,
		SortOrder:  req.SortOrder,
		IsEnabled:  true,
		IsSystem:   false,
		CreatedBy:  createdBy,
	}

	if err := s.repo.CreateEmoji(emoji); err != nil {
		return nil, err
	}

	log.Printf("[表情] 创建表情: %s (%s)", emoji.Name, emoji.Code)
	return emoji, nil
}

// GetEmoji 获取表情详情
func (s *emojiService) GetEmoji(id uint) (*model.Emoji, error) {
	emoji, err := s.repo.GetEmojiByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, errors.New("表情不存在")
		}
		return nil, err
	}
	return emoji, nil
}

// GetEmojiList 获取表情列表
func (s *emojiService) GetEmojiList(req *model.EmojiListReq) (*model.EmojiListResp, error) {
	// 参数验证
	if req.Page < 1 {
		req.Page = 1
	}
	if req.PageSize < 1 || req.PageSize > 100 {
		req.PageSize = 20
	}

	emojis, total, err := s.repo.GetEmojiList(req)
	if err != nil {
		return nil, err
	}

	return &model.EmojiListResp{
		List:     emojis,
		Total:    total,
		Page:     req.Page,
		PageSize: req.PageSize,
	}, nil
}

// UpdateEmoji 更新表情
func (s *emojiService) UpdateEmoji(id uint, req *model.UpdateEmojiReq) error {
	// 检查表情是否存在
	emoji, err := s.repo.GetEmojiByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("表情不存在")
		}
		return err
	}

	// 系统表情不允许禁用
	if emoji.IsSystem && req.IsEnabled != nil && !*req.IsEnabled {
		return errors.New("系统内置表情不能禁用")
	}

	// 如果修改分类，检查新分类是否存在
	if req.CategoryID != nil {
		_, err := s.repo.GetCategoryByID(*req.CategoryID)
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				return errors.New("目标分类不存在")
			}
			return err
		}
	}

	// 构建更新字段
	updates := make(map[string]interface{})
	if req.CategoryID != nil {
		updates["category_id"] = *req.CategoryID
	}
	if req.Name != "" {
		updates["name"] = req.Name
	}
	if req.ImageURL != "" {
		updates["image_url"] = req.ImageURL
	}
	if req.Emoji != "" {
		updates["emoji"] = req.Emoji
	}
	if req.SortOrder != nil {
		updates["sort_order"] = *req.SortOrder
	}
	if req.IsEnabled != nil {
		updates["is_enabled"] = *req.IsEnabled
	}

	if len(updates) == 0 {
		return errors.New("没有需要更新的字段")
	}

	if err := s.repo.UpdateEmoji(id, updates); err != nil {
		return err
	}

	log.Printf("[表情] 更新表情 ID: %d", id)
	return nil
}

// DeleteEmoji 删除表情
func (s *emojiService) DeleteEmoji(id uint) error {
	// 检查表情是否存在
	emoji, err := s.repo.GetEmojiByID(id)
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return errors.New("表情不存在")
		}
		return err
	}

	// 系统表情不允许删除
	if emoji.IsSystem {
		return errors.New("系统内置表情不能删除")
	}

	if err := s.repo.DeleteEmoji(id); err != nil {
		return err
	}

	log.Printf("[表情] 删除表情 ID: %d", id)
	return nil
}

// ==================== 前端获取表情包 ====================

// GetEmojis 获取所有表情包（按分类组织）
func (s *emojiService) GetEmojis() (*model.GetEmojisResp, error) {
	categories, err := s.repo.GetAllEmojisByCategoriesWithEmojis()
	if err != nil {
		return nil, err
	}

	return &model.GetEmojisResp{
		Categories: categories,
	}, nil
}

// GetHotEmojis 获取热门表情
func (s *emojiService) GetHotEmojis(limit int) ([]model.Emoji, error) {
	if limit <= 0 || limit > 50 {
		limit = 20
	}

	return s.repo.GetHotEmojis(limit)
}

// RecordEmojiUsage 记录表情使用（用于统计热门表情）
func (s *emojiService) RecordEmojiUsage(emojiID uint) error {
	return s.repo.IncrementUsageCount(emojiID)
}

